<template>
	<view class="addTask">
		<view class="addTask">
			<view class="top">
				<view class="com df" style="border: 1;height: auto;">
					<view class="df">
						<view class="tt">新增地址</view>
					</view>
					<view class="">
						<u--text prefixIcon="plus" iconStyle="font-size: 38rpx;color:#00c792;margin-right:10rpx" color="#eb8900" text="新增" @click="popOpen(null,'新增')"></u--text>
					</view>
				</view>
				<u-radio-group v-if="raidoChangeFlash" placement="column" v-model="radioValue"  activeColor="#00c792">
					<view class="com df" style="border: 1;" v-for="(item,index) in address" :key='index'>
						<view style="width: 83%;">
							<u-radio labelSize="12" :label="item.provinceName+item.cityName+item.detailInfo" :name="item.id" @change="radioChange(item)"></u-radio>
							<view style="margin-left: 44rpx;margin-top: 20rpx;">
								<u-text bold color="#343434" size="24rpx" :text="item.userName+' '+item.telNum"></u-text>
							</view>
						</view>
						<view style="text-align: center;">
							<u--text prefixIcon="trash" iconStyle="font-size: 38rpx;color:#d4040e;margin-right:10rpx" color="#d4040e" text="删除" @click="delAddress(item)"></u--text>
							<u--text prefixIcon="edit-pen" iconStyle="font-size: 38rpx;color:#eb8900;margin-right:10rpx" color="#eb8900" text="编辑" @click="popOpen(item,'编辑')"></u--text>
						</view>
					</view>
				</u-radio-group>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom">
			<view class="box" style="height:100%">
				<view class="form-box">
					<view class="">
						<u--text :text="title" type="primary" bold></u--text>
					</view>
					<u-form labelPosition="left" :model="formData" :rules="rules" ref="uForm" labelWidth="70">
						<u-form-item label="收货人:" prop="userName">
							<u-input placeholder="收货人姓名" v-model="formData.userName" suffixIcon="account"></u-input>
						</u-form-item>
						<u-form-item label="电话:" prop="telNum">
							<u-input placeholder="收货人电话" type="number" maxlength="11" v-model="formData.telNum" suffixIcon="phone"></u-input>
						</u-form-item>
						<u-form-item label="地址:">
							<view style="width: 180rpx;margin-left: 30rpx;">
								<u-tag  text="选取地区" size="mini" icon="map" @click="selectAddress"></u-tag>
							</view>
						</u-form-item>
						<u-form-item label="收货地区:" v-if="currentLocation">
							<view style="margin-left: 30rpx;">
								<u--text type="info" :text="currentLocation"></u--text>
							</view>
						</u-form-item>
						<u-form-item label="详细地址:" v-if="currentLocation">
							<view style="margin-left: 30rpx;">
								<u--input :customStyle="{height:'20rpx'}" v-model="addressDetail" placeholder="请输入详细地址" clearable></u--input>
							</view>
						</u-form-item>
					</u-form>
				</view>
				<view class="buttons">
					<u-button text="取消"   size="small" @click="cancel"></u-button>
					<u-button text="确定" type="success" hairline size="small" color="#17CC77" @click="comfirm"></u-button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {getUserAllAddress,addOrEditAddress,delAddress} from "@/api/api.js"
	var that = this
	export default {
		data() {
				return {
					title:'新增地址',
					currentEditAddressId:'',
					radioValue:'',
					address:[],
					current:0,
					addressDetail:'',
					formData:{
						userName:'',
						provinceName:'',
						cityName:'',
						detailInfo:'',
						telNum:'',
						isDefault:'',
						districtName:'',
					},
					raidoChangeFlash:true,
					currentLocation:'',
					location:{},
					flag:false,
					rules: {
						userName: {
							type: 'string',
							required: true,
							message: '请填写姓名',
							trigger: ['blur', 'change']
						},
						telNum: [{
								required: true,
								message: '请输入手机号',
								trigger: ['change', 'blur'],
							},
							{
								// 自定义验证函数，见上说明
								validator: (rule, value, callback) => {
									// 上面有说，返回true表示校验通过，返回false表示不通过
									// uni.$u.test.mobile()就是返回true或者false的
									return uni.$u.test.mobile(value);
								},
								message: '手机号码不正确',
								// 触发器可以同时用blur和change
								trigger: ['change', 'blur'],
							}
						],
					},
				}
			},
			onReady() {
				this.$refs.uForm.setRules(this.rules)
			},
			onLoad(params){
				console.log(params);
				if(params.hasLocation == 'true'){
					this.flag = true
					this.checkLocation()
				}
			},
			onShow() {
				this.getAddressList()
				uni.$on("sendLocation",(location)=>{
					if(location){
						this.saveLocation(location)
					}
				})
			},
			onUnload() {
				uni.setStorageSync("pickedFormData",{})
			},
			destroyed() {
				uni.setStorageSync("pickedFormData",{})
			},
			methods: {
				 delAddress(item){
					uni.showModal({
						title:"提示",
						content:"确认删除该地址？",
						 success: async (res)=>{
							if(res.confirm){
								uni.showLoading({
									mask:true
								})
								let id = item.id
								const res = await delAddress(id)
								try{
									if(res?.data.code == 200){
										uni.hideLoading()
										uni.showToast({
											title:res.data.msg,
											icon:"success"
										})
										setTimeout(()=>{
											uni.redirectTo({
												url:"/pages/user/profileEdit"
											})
										},1000)
									}else{
										uni.hideLoading()
										uni.showToast({
											title:res.data.msg,
											icon:"error"
										})
									}
								}catch(e){
									//TODO handle the exception
									uni.hideLoading()
									uni.showToast({
										title:e,
										icon:"error"
									})
									throw e
								}
							}else{
								uni.showToast({
									title:"取消删除",
									icon:"none"
								})
							}
						}
					})
				},
				radioChange: function(item) {
					item.ifDefault = true
					console.log(item);
					this.addNewAddress(item)
				},
				checkLocation(){
					if(this.flag){
						let data = uni.getStorageSync("pickedFormData")
						if(data){
							console.log('执行检测是否有地址',data);
							this.formData.userName = data.userName
							this.formData.telNum = data.telNum
							this.currentLocation = data.provinceName+data.cityName+data.districtName
							this.addressDetail = data.detailInfo
							data.id = uni.getStorageSync('EditAddressId')
							this.popOpen(data,uni.getStorageSync('addressAction'))
						}
					}
				},
				saveLocation(data){
					this.location = data
					this.formData.cityName = this.location.cityname
					this.formData.provinceName = this.location.pname
					this.formData.districtName = this.location.adname
					this.formData.detailInfo = this.location.name || this.location.title
					console.log(this.formData,'@@@@@');
					this.formData.isDefault = "0"
					uni.setStorageSync("pickedFormData",this.formData)
				},
				submit(formData){
					this.currentEditAddressId = uni.getStorageSync('EditAddressId')
					if(this.currentEditAddressId){
						formData.id = this.currentEditAddressId
					}
					console.log(this.currentEditAddressId);
					if(!formData.detailInfo){
						uni.showToast({
							title:"请选取收货地址",
							icon:"error",
							mask:true
						})
						return
					}
					console.log('_______',formData);
					this.addNewAddress(formData)
					this.$refs.popup.close()
					this.getAddressList()
				},
				comfirm(){
					this.$refs.uForm.validate().then(res=>{
						console.log(res);
						if(res){
							this.title = uni.getStorageSync('addressAction')
							if(this.title == '编辑'){
								let formData = uni.getStorageSync("pickedFormData")
								formData.userName = this.formData.userName
								formData.telNum = this.formData.telNum
								formData.ifDefault = true
								formData.isDefault = 0
								formData.detailInfo = this.addressDetail
								this.submit(formData)
							}else{
								let formData = uni.getStorageSync("pickedFormData")
								this.submit(formData)
							}
						}else{
							uni.$u.toast('请填写信息')
						}
					})
					
				},
				cancel(){
					this.formData = {
						userName:'',
						provinceName:'',
						cityName:'',
						detailInfo:'',
						telNum:'',
						isDefault:''
					}
					this.currentLocation = ''
					this.location = {}
					this.$refs.popup.close()
				},
				popOpen(item,action){
					if(action){
						uni.setStorageSync('addressAction',action)
						this.title = action
					}
					if(item){
						this.formData.userName = item.userName
						this.formData.telNum = item.telNum
						this.formData.provinceName = item.provinceName
						this.formData.cityName = item.cityName
						this.formData.districtName = item.districtName
						this.formData.detailInfo = item.detailInfo
						this.formData.ifDefault = item.ifDefault
						this.currentLocation = item.provinceName+item.cityName+(item.districtName || " ")
						this.addressDetail = item.detailInfo
						this.currentEditAddressId = item.id
						uni.setStorageSync('EditAddressId',item.id)
						uni.setStorageSync("pickedFormData",this.formData)
					}else{
						uni.setStorageSync('EditAddressId','')
					}
					this.$refs.popup.open()
				},
				async addNewAddress(formData){
					this.raidoChangeFlash = false
					const res = await addOrEditAddress(formData)
					if(res?.data.code == 200){
						uni.showToast({
							title:res.data.msg,
							icon:"success"
						})
					}else{
						uni.showToast({
							title:res.data.msg,
							icon:"error"
						})
					}
					this.getAddressList()
				},
				async getAddressList(){
					uni.showLoading({
						mask:true,
					})
					const res = await getUserAllAddress()
					if(res?.data.code == 200){
						this.address = res.data.data
						let isDefaultAddress = this.address.filter(item=> item.isDefault == 1)
						this.radioValue = isDefaultAddress[0]?.id || ''
						uni.hideLoading()
						this.raidoChangeFlash = true
					}else{
						uni.showToast({
							title:"获取地址失败",
							mask:true,
							icon:"error"
						})
						uni.hideLoading()
					}
				},
				selectAddress(){
					console.log('点击了编辑地址');
					uni.navigateTo({
						url:"/pages/user/map"
					})
				},
			}
		}
</script>

<style lang="scss" scoped>
	::v-deep .vue-ref{
		padding-bottom: 0 !important;
	}
	.box{
		background-color: #FFFFFF;
		border-top-right-radius: 24rpx;
		border-top-left-radius: 24rpx;
		width: 100%;
		height: 660rpx;
		.form-box{
			padding: 50rpx;
			padding-bottom: 0;
		}
		.buttons{
			display: flex;
			justify-content: space-around;
			padding: 60rpx;
			:nth-child(2){
				margin-left: 20rpx;
			}
		}
	}
	.fontColor{
		color:#CF4033;
	}
	.mask{
		background-color: #efefef;
		border-radius: 24rpx;
		height: 280rpx;
		width: 690rpx;
		position: relative;
		.picture{
			display: inline-block;
			margin: 20rpx;
		}
		
		.desc{
			font-family: Verdana, Geneva, Tahoma, sans-serif;
			top:20rpx;
			position: absolute;
		}
	}
	.location-container{
		display: flex;
		justify-content: space-between;
		align-items: center;
		.profile{
			padding: 20rpx;
			view text:nth-child(1){
				font-weight: 600;
				font-size: 30rpx;
			}
			view text:nth-child(2){
				font-size: 28rpx;
				margin-left: 30rpx;
			}
			.location{
				margin-top: 20rpx;
				color: #737373;
				font-size: 26rpx;
			}
		}
	}
	.center{
		justify-content: center !important;
		align-items: center !important;
	}
	.addTask {
		.df {
			display: flex;
		}
		
		.top {
			width: 690rpx;
			// height: 108rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 0, 0, 0.12);
			border-radius: 0rpx 0rpx 36rpx 36rpx;
			padding: 0 30rpx;
			border-top: 1px solid rgba(0, 0, 0, 0.12);

			.com {
				justify-content: space-between;
				align-items: center;
				font-size: 30rpx;
				height: 80rpx;
				padding: 20rpx 0;
				border-bottom: 1rpx solid rgba(0, 0, 0, 0.12);

				.tt {
					color: rgba(68, 78, 104, 0.7);
				}

				.type {
					// color: #17CC77;

					.text {
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
						width: 382rpx;
						font-size: 28rpx;
						margin-right: 18rpx;
					}

					.input {
						margin-top: -20rpx;
						width: 180rpx;
					}

					.image {
						width: 12rpx;
						height: 22rpx;

						image {
							margin-top: 10rpx;
							width: 12rpx;
							height: 22rpx;
						}
					}
				}
			}
		}

		.btn {
			position: absolute;
			bottom: 91rpx;
			left: 50%;
			margin-left: -140rpx;
			width: 280rpx;
			height: 84rpx;
			background: #1BC46D;
			box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(27, 196, 109, 0.4);
			border-radius: 12rpx;
			color: #FFFFFF;
			font-size: 32rpx;
			text-align: center;
			line-height: 84rpx;
		}
	}
</style>